const audio = document.querySelector('audio')
const canvas = document.querySelector('#canvas')
const ctx = canvas.getContext('2d')
let isInit = false

function initCanvas(){
    canvas.width = document.body.clientWidth
    canvas.height = window.innerHeight / 2 * devicePixelRatio
}

initCanvas()

function draw(){
    const {width,height} = canvas
    ctx.clearRect(0,0,width,height)
    requestAnimationFrame(draw)
    analyser.getByteFrequencyData(dataArray)
    const len = dataArray.length
    ctx.fillStyle = 'pink'
    let barWidth = width / len
    for(let i = 0;i<len;i++){
        let data = dataArray[i]
        let barHeight = data / 255 * height
        let x1 = barWidth * i
        let y1 = height - barHeight
        ctx.fillRect(x1,y1,barWidth,barHeight)
    }
}
let dataArray,analyser
audio.onplay = function(){
    if(isInit) return
// 首先获取音频的上下文
const audCtx = new AudioContext()
const source = audCtx.createMediaElementSource(audio) // 创建一个音频源节点
console.log('audCtx',audCtx);
console.log('source',source);

// 创建一个分析器
analyser = audCtx.createAnalyser()
analyser.fftSize = 512
console.log(analyser.frequencyBinCount);
dataArray = new Uint8Array(analyser.frequencyBinCount)
source.connect(analyser)
analyser.connect(audCtx.destination)
// analyser.getByteFrequencyData(dataArray)
// console.log(dataArray);
isInit = true
draw()
}